package websocketgulu.demo.Utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

/**
 * 16进制转换工具
 */
@Slf4j
public class HexEcodeUtil {

    //16进制数字字符集
    public static final String HEXMAXSTRING = "0123456789ABCDEF";
    public static final String HEXMINSTRING = "0123456789abcdef";
    /**
     * byte转Str
     *
     * @param b
     */
    public static String ByteArrayToAsc(byte b){

        // 我们把补码当作原码计算
        int out = b & 0xff;
//        System.out.println(out);
//        return AscStr;
        return StrToHexStr(out);
    }

    /**
     * Str转HEX
     *
     * @param out
     * @return
     */
    public static String StrToHexStr(int out) {

        StringBuilder stringBuilder = new StringBuilder(10);
        //将字节数组中每个字节拆解成2位16进制整数

        stringBuilder.append(HEXMAXSTRING.charAt(( out& 0xf0) >> 4));
        stringBuilder.append(HEXMAXSTRING.charAt((out & 0x0f) >> 0));
        return stringBuilder.toString();
    }


    /**
     *
     * @param data 一个byte数组
     * @return 返回一个int数组
     */
    public static int[] byteToIntArray(byte[] data){
        int[] intData = new int[1024];
        for(int i = 0; i < 1024; i++ ){
            intData[i] = data[i] & 0xff;
            if( intData[i] > 127 )
                intData[i] = intData[i] - 256;
        }
        return intData;
    }

}